<template>
  <div class="knowledge-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="left">
            <span>知识列表</span>
          </div>
          <div class="right">
            <el-button type="primary" @click="handleCreate">新增知识</el-button>
          </div>
        </div>
      </template>
      
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="分类">
          <el-select v-model="queryParams.categoryId" placeholder="全部分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题">
          <el-input v-model="queryParams.title" placeholder="请输入标题" clearable />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        v-loading="loading"
        :data="knowledgeList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="ID" prop="id" width="80" />
        
        <el-table-column label="标题" prop="title" min-width="180" show-overflow-tooltip />
        
        <el-table-column label="副标题" prop="subtitle" min-width="180" show-overflow-tooltip />
        
        <el-table-column label="分类" width="120">
          <template #default="{ row }">
            <el-tag>{{ getCategoryName(row.categoryId) }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="内容预览" prop="content" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.content" class="content-preview">{{ getContentPreview(row.content) }}</span>
            <span v-else class="no-content">暂无内容</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <div class="batch-actions" v-if="selectedIds.length > 0">
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>
    </el-card>
    
    <!-- 新增/编辑知识弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑知识' : '新增知识'"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="knowledgeFormRef"
        :model="knowledgeForm"
        :rules="knowledgeRules"
        label-width="80px"
      >
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="knowledgeForm.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="knowledgeForm.title" placeholder="请输入标题" />
        </el-form-item>
        
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="knowledgeForm.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="knowledgeForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看知识详情弹窗 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="知识详情"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentKnowledge" class="knowledge-detail">
        <div class="knowledge-header">
          <h2 class="title">{{ currentKnowledge.title }}</h2>
          <div class="meta">
            <el-tag>{{ getCategoryName(currentKnowledge.categoryId) }}</el-tag>
            <span class="subtitle">{{ currentKnowledge.subtitle }}</span>
          </div>
        </div>
        
        <div class="knowledge-content">
          <div class="markdown-body">
            {{ currentKnowledge.content }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getKnowledgePage,
  getKnowledgeDetail,
  addKnowledge,
  updateKnowledge,
  deleteKnowledge,
  batchDeleteKnowledge
} from '@/api/knowledge'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const knowledgeList = ref([])
const total = ref(0)
const selectedIds = ref([])
const currentKnowledge = ref(null)
const knowledgeFormRef = ref(null)

// 分类选项
const categoryOptions = [
  { value: 1, label: '中药基础' },
  { value: 2, label: '针灸推拿' },
  { value: 3, label: '养生保健' },
  { value: 4, label: '经典理论' },
  { value: 5, label: '四季养生' },
  { value: 6, label: '食疗方案' }
]

// 查询参数
const queryParams = reactive({
  categoryId: undefined,
  title: '',
  pageNum: 1,
  pageSize: 10
})

// 表单数据
const knowledgeForm = reactive({
  id: 0,
  categoryId: undefined,
  title: '',
  subtitle: '',
  content: ''
})

// 表单验证规则
const knowledgeRules = {
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  subtitle: [
    { required: true, message: '请输入副标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryOptions.find(item => item.value === categoryId)
  return category ? category.label : '未知分类'
}

// 获取内容预览
const getContentPreview = (content) => {
  if (!content) return ''
  return content.length > 50 ? content.substring(0, 50) + '...' : content
}

// 获取知识列表
const fetchKnowledgeList = async () => {
  loading.value = true
  try {
    const { data } = await getKnowledgePage({
      ...queryParams,
      categoryId: queryParams.categoryId || undefined,
      title: queryParams.title || undefined
    })
    knowledgeList.value = data || []
    total.value = data.length
  } catch (error) {
    console.error('获取知识列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 查询
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchKnowledgeList()
}

// 重置查询
const resetQuery = () => {
  queryParams.categoryId = undefined
  queryParams.title = ''
  queryParams.pageNum = 1
  fetchKnowledgeList()
}

// 每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchKnowledgeList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchKnowledgeList()
}

// 新增知识
const handleCreate = () => {
  isEdit.value = false
  knowledgeForm.id = 0
  knowledgeForm.categoryId = undefined
  knowledgeForm.title = ''
  knowledgeForm.subtitle = ''
  knowledgeForm.content = ''
  dialogVisible.value = true
}

// 编辑知识
const handleEdit = async (row) => {
  try {
    const { data } = await getKnowledgeDetail(row.id)
    isEdit.value = true
    
    knowledgeForm.id = data.id
    knowledgeForm.categoryId = Number(row.categoryId ) //修改
    knowledgeForm.title = data.title
    knowledgeForm.subtitle = data.subtitle
    knowledgeForm.content = data.content
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取知识详情失败:', error)
    ElMessage.error('获取知识详情失败')
  }
}

// 查看知识详情
const handleView = async (row) => {
  try {
    const { data } = await getKnowledgeDetail(row.id)
    currentKnowledge.value = {
      ...data,
      categoryId: row.categoryId
    }
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取知识详情失败:', error)
    ElMessage.error('获取知识详情失败')
  }
}

// 删除知识
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该知识吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteKnowledge(row.id)
    ElMessage.success('删除成功')
    fetchKnowledgeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除知识失败:', error)
      ElMessage.error('删除知识失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除这 ${selectedIds.value.length} 条记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await batchDeleteKnowledge(selectedIds.value)
    ElMessage.success('批量删除成功')
    fetchKnowledgeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!knowledgeFormRef.value) return
  
  await knowledgeFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      if (isEdit.value) {
        await updateKnowledge(knowledgeForm)
        ElMessage.success('更新成功')
      } else {
        await addKnowledge(knowledgeForm)
        ElMessage.success('添加成功')
      }
      
      dialogVisible.value = false
      fetchKnowledgeList()
    } catch (error) {
      console.error(isEdit.value ? '更新知识失败:' : '添加知识失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
    } finally {
      submitting.value = false
    }
  })
}

onMounted(() => {
  fetchKnowledgeList()
})
</script>

<style lang="scss" scoped>
.knowledge-manage-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .batch-actions {
    margin-top: 16px;
  }
  
  .content-preview {
    font-size: 13px;
    color: #606266;
  }
  
  .no-content {
    font-size: 13px;
    color: #909399;
    font-style: italic;
  }
  
  .knowledge-detail {
    .knowledge-header {
      margin-bottom: 24px;
      
      .title {
        margin: 0 0 12px;
        font-size: 20px;
        color: #303133;
      }
      
      .meta {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .subtitle {
          font-size: 14px;
          color: #606266;
        }
      }
    }
    
    .knowledge-content {
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 4px;
      
      .markdown-body {
        font-size: 14px;
        line-height: 1.8;
        white-space: pre-line;
      }
    }
  }
}
</style> 